<template>
  <div class="profile-container">
    <el-card class="profile-header" v-loading="loading">
      <div class="header-content">
        <div class="avatar-section">
          <div class="avatar-wrapper" @click="openAvatarUpload">
            <el-avatar :size="120" :src="userInfo.avatar ||
              'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
              " class="user-avatar" />
            <div class="avatar-mask">
              <el-icon>
                <Camera />
              </el-icon>
              <span>更换头像</span>
            </div>
          </div>
          <div class="avatar-info">
            <h2 class="user-name">
              {{ userInfo.nickname || userInfo.username }}
            </h2>
            <p class="user-username">@{{ userInfo.username }}</p>
            <div class="user-meta">
              <span>
                <el-icon>
                  <Message />
                </el-icon>
                {{ userInfo.email }}
              </span>
              <span>
                <el-icon>
                  <Calendar />
                </el-icon>
                加入于 {{ formatDate(userInfo.created_at) }}
              </span>
            </div>
          </div>
        </div>

        <div class="header-actions">
          <el-button type="primary" @click="openEditDialog">
            <el-icon>
              <Edit />
            </el-icon>
            编辑资料
          </el-button>
          <el-button @click="openPasswordDialog">
            <el-icon>
              <Lock />
            </el-icon>
            修改密码
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 快捷链接 -->
    <div class="quick-links-section">
      <h3 class="section-title">
        <el-icon>
          <Star />
        </el-icon>
        快捷入口
      </h3>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="link in quickLinks" :key="link.route">
          <el-card shadow="hover" class="link-card" @click="router.push(link.route)">
            <div class="link-icon" :style="{ background: link.color }">
              <el-icon :size="28">
                <component :is="link.icon" />
              </el-icon>
            </div>
            <h4 class="link-title">{{ link.title }}</h4>
            <p class="link-desc">{{ link.desc }}</p>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 账号信息 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <User />
          </el-icon>
          <span>账号信息</span>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">
          {{ userInfo.id }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ userInfo.username }}
        </el-descriptions-item>
        <el-descriptions-item label="昵称">
          {{ userInfo.nickname || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ userInfo.email }}
        </el-descriptions-item>
        <el-descriptions-item label="账号状态">
          <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
            {{ userInfo.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">
          {{ formatDate(userInfo.created_at) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑个人资料" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="450px">
      <el-form :model="passwordForm" label-width="90px">
        <el-form-item label="原密码">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（至少6位）" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="更换头像" width="450px">
      <div class="upload-container">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="() => false"
          :on-change="handleAvatarSuccess" :disabled="uploadingAvatar" accept="image/*">
          <div v-if="uploadedImageUrl" class="avatar-preview">
            <img :src="uploadedImageUrl" class="preview-image" />
          </div>
          <div v-else class="upload-placeholder">
            <el-icon class="upload-icon" v-if="!uploadingAvatar">
              <Plus />
            </el-icon>
            <el-icon class="upload-icon uploading" v-else>
              <Loading />
            </el-icon>
            <div class="upload-text">
              {{ uploadingAvatar ? '上传中...' : '点击选择图片' }}
            </div>
            <div class="upload-hint">支持 JPG、PNG 格式，大小不超过 2MB</div>
          </div>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUploadedAvatar" :disabled="!uploadedImageUrl || uploadingAvatar"
          :loading="uploadingAvatar">
          保存头像
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  getUserInfo,
  updateProfile as updateProfileApi,
  changePassword as changePasswordApi
} from '../../api/auth'
import { uploadImage } from '../../api/upload'
import {
  User,
  Star,
  Calendar,
  Message,
  Camera,
  Edit,
  Lock,
  Key,
  Plus,
  Notebook,
  Location,
  StarFilled,
  FolderOpened,
  Document,
  Loading
} from '@element-plus/icons-vue'

const router = useRouter()

// 用户信息
const userInfo = ref({
  id: 0,
  username: '',
  email: '',
  role: '',
  nickname: '',
  avatar: '',
  created_at: '',
  status: 1
})

// 加载状态
const loading = ref(true)

// 编辑对话框
const editDialogVisible = ref(false)
const editForm = ref({
  nickname: '',
  email: ''
})

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载用户信息
const loadUserInfo = async () => {
  loading.value = true
  try {
    const result = await getUserInfo()
    if (result.success) {
      userInfo.value = result.data
      editForm.value = {
        nickname: result.data.nickname || '',
        email: result.data.email || ''
      }
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const openEditDialog = () => {
  editDialogVisible.value = true
}

// 保存个人信息
const saveProfile = async () => {
  try {
    const result = await updateProfileApi({
      nickname: editForm.value.nickname,
      email: editForm.value.email
    })

    if (result.success) {
      ElMessage.success('个人信息已更新')
      editDialogVisible.value = false

      // 更新本地存储
      const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
      user.nickname = result.data.nickname
      user.email = result.data.email
      localStorage.setItem('userInfo', JSON.stringify(user))

      // 触发自定义事件，通知 MainLayout 刷新
      window.dispatchEvent(new Event('userInfoUpdated'))

      // 重新加载
      loadUserInfo()
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('更新资料失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 打开修改密码对话框
const openPasswordDialog = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordDialogVisible.value = true
}

// 修改密码
const changePassword = async () => {
  if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入密码不一致')
    return
  }

  if (passwordForm.value.newPassword.length < 6) {
    ElMessage.error('密码长度至少6个字符')
    return
  }

  try {
    const result = await changePasswordApi({
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    })

    if (result.success) {
      ElMessage.success('密码修改成功，请重新登录')
      passwordDialogVisible.value = false

      // 清除登录信息，刷新页面让用户重新登录
      setTimeout(() => {
        localStorage.removeItem('userToken')
        localStorage.removeItem('userInfo')
        window.location.href = '/'
      }, 1500)
    } else {
      ElMessage.error(result.message || '修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改失败，请重试')
  }
}

// 头像上传相关
const uploadDialogVisible = ref(false)
const uploadedImageUrl = ref('')
const uploadingAvatar = ref(false)

// 打开头像上传对话框
const openAvatarUpload = () => {
  uploadedImageUrl.value = ''
  uploadDialogVisible.value = true
}

// 处理头像上传
const handleAvatarSuccess = async (uploadFile) => {
  const file = uploadFile.raw || uploadFile

  if (!beforeAvatarUpload(file)) {
    return
  }

  uploadingAvatar.value = true

  try {
    const result = await uploadImage(file)

    if (result.success) {
      uploadedImageUrl.value = result.data.url
      ElMessage.success('图片上传成功，请点击保存按钮更新头像')
    } else {
      ElMessage.error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    uploadingAvatar.value = false
  }
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 保存上传的头像
const saveUploadedAvatar = async () => {
  if (!uploadedImageUrl.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  try {
    const result = await updateProfileApi({
      avatar: uploadedImageUrl.value
    })

    if (result.success) {
      ElMessage.success('头像更新成功！')
      uploadDialogVisible.value = false
      uploadedImageUrl.value = ''

      // 更新本地存储
      const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
      user.avatar = result.data.avatar
      localStorage.setItem('userInfo', JSON.stringify(user))

      // 触发自定义事件，通知 MainLayout 刷新
      window.dispatchEvent(new Event('userInfoUpdated'))

      // 重新加载
      loadUserInfo()
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('头像更新失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 快捷链接
const quickLinks = [
  {
    title: '我的游记',
    icon: Notebook,
    desc: '查看和管理你发布的游记',
    route: '/travel-note',
    color: '#667eea'
  },
  {
    title: '我的旅行计划',
    icon: Location,
    desc: '管理你的旅行计划和行程',
    route: '/travel-plan',
    color: '#f093fb'
  },
  {
    title: '我的收藏',
    icon: FolderOpened,
    desc: '查看你收藏的精彩内容',
    route: '/profile/favorites',
    color: '#4facfe'
  },
  {
    title: '我的喜欢',
    icon: StarFilled,
    desc: '查看你点赞过的内容',
    route: '/profile/likes',
    color: '#ff6b6b'
  }
]

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 头部卡片 */
.profile-header {
  margin-bottom: 30px;
  border-radius: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.profile-header :deep(.el-card__body) {
  padding: 40px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.avatar-section {
  display: flex;
  gap: 24px;
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
}

.user-avatar {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  border: 4px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 14px;
  gap: 4px;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.avatar-wrapper:hover .user-avatar {
  transform: scale(1.05);
}

.avatar-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: white;
}

.user-name {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.user-username {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

.user-meta {
  display: flex;
  gap: 24px;
  font-size: 14px;
  margin-top: 8px;
  opacity: 0.85;
}

.user-meta span {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.header-actions .el-button--primary {
  background: rgba(255, 255, 255, 0.95);
  color: #667eea;
}

.header-actions .el-button--primary:hover {
  background: white;
}

/* 快捷链接 */
.quick-links-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.link-card {
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.link-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.link-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin: 0 auto 16px;
}

.link-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.link-desc {
  margin: 0;
  font-size: 14px;
  color: #6b7280;
}

/* 详细信息卡片 */
.detail-card {
  border-radius: 12px;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-card :deep(.el-descriptions__label) {
  font-weight: 500;
  color: #374151;
}

.detail-card :deep(.el-descriptions__content) {
  color: #1a1a1a;
}

/* 头像上传 */
.upload-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.avatar-uploader {
  width: 200px;
}

.avatar-preview {
  width: 200px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  border: 2px dashed #d9d9d9;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-preview:hover {
  border-color: #409eff;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  width: 200px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-placeholder:hover {
  border-color: #667eea;
  background: #f0f2ff;
}

.upload-icon {
  font-size: 48px;
  color: #8c939d;
  margin-bottom: 12px;
}

.upload-icon.uploading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  text-align: center;
  padding: 0 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
  }

  .header-actions {
    width: 100%;
  }

  .header-actions .el-button {
    flex: 1;
  }

  .avatar-section {
    flex-direction: column;
    text-align: center;
  }

  .user-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
